package com.qmx.launcher.service;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.qmx.launcher.receiver.UsbReceiver;

/**
 * @author chengxiangtong
 * @date 2018/11/28
 * version : 1.0
 * class describe：监听U盘插拔
 */
public class UsbService extends Service {
    private Callback callback;
    private UsbReceiver usbReceiver;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    public class Binder extends android.os.Binder {
        public UsbService getService() {
            return UsbService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
        iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        iFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
        iFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        iFilter.addDataScheme("file");
        usbReceiver = new UsbReceiver(new UsbReceiver.DataCallBack() {
            @Override
            public void onDataChanged(String path, String fileName) {
                if (callback != null) {
                    callback.onDataChange(path, fileName);
                    Log.i("onDataChanged", "onCreateonCreate");
                }
            }
        });
        registerReceiver(usbReceiver, iFilter);

        Log.i("UsbService", "onCreateonCreate");
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public interface Callback {
        void onDataChange(String path, String fileName);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(usbReceiver);
    }
}
